package com.sufen.seckill.service.impl;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sufen.seckill.exception.GlobalException;
import com.sufen.seckill.mapper.OrderMapper;
import com.sufen.seckill.pojo.Order;
import com.sufen.seckill.pojo.SeckillGoods;
import com.sufen.seckill.pojo.SeckillOrder;
import com.sufen.seckill.pojo.User;
import com.sufen.seckill.service.IGoodsService;
import com.sufen.seckill.service.IOrderService;
import com.sufen.seckill.service.ISeckillGoodsService;
import com.sufen.seckill.service.ISeckillOrderService;
import com.sufen.seckill.utils.MD5UTIL;
import com.sufen.seckill.utils.UUIDUtil;
import com.sufen.seckill.vo.GoodsVo;
import com.sufen.seckill.vo.OrderDetailVo;
import com.sufen.seckill.vo.RespBeanEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.thymeleaf.util.StringUtils;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhoubin
 * @since 2021-10-20
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Autowired
    private ISeckillGoodsService seckillGoodsService;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ISeckillOrderService seckillOrderService;

    @Autowired
    private IGoodsService goodsService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Transactional
    @Override
    public Order seckill(User user, GoodsVo goods) {
//        synchronized (this){
//
//        }
        //1.秒杀商品表减库存
        SeckillGoods seckillGoods=seckillGoodsService.getById(goods.getId());
        seckillGoods.setStockCount(seckillGoods.getStockCount()-1);
//        seckillGoodsService.updateById(seckillGoods);
        //解决超卖:1.判断库存>0
        //这里的mybatis的减1和判断>0是合并原子操作，因此可以解决问题
//        Boolean seckillGoodsResult=seckillGoodsService.update(new UpdateWrapper<SeckillGoods>().set("stock_count",seckillGoods.getStockCount()).eq("id",seckillGoods.getId()).gt("stock_count",0));
        Boolean seckillGoodsResult=seckillGoodsService.update(new UpdateWrapper<SeckillGoods>().setSql("stock_count=stock_count-1").eq("goods_id",goods.getId()).gt("stock_count",0));
        if(seckillGoods.getStockCount()<1){
            redisTemplate.opsForValue().set("isStockEmpty:"+goods.getId(),"0");
            return null;
        }
        //2.创建订单表的行记录
        Order order=new Order();
        order.setUserId(user.getId());
        order.setGoodsId(goods.getId());
        order.setDeliveryAddrId(0L);
        order.setGoodsName(goods.getGoodsName());
        order.setGoodsCount(1);
        order.setGoodsPrice(goods.getGoodsPrice());
        order.setOrderChannel(1);
        order.setStatus(0);
        order.setCreateDate(new Date());
        orderMapper.insert(order);
        //3.创建秒杀订单表的行记录
        //这里给seckillOrder表的user_id字段和goods_id字段加上了联合索引。防止有一样的用户重复抢购同一样商品。
        //不成功可能会通过@transactional注解回滚，这样之前库存-1也就回滚了，完成了需求
        SeckillOrder seckillOrder=new SeckillOrder();
        seckillOrder.setUserId(user.getId());
        seckillOrder.setOrderId(order.getId());
        seckillOrder.setGoodsId(goods.getId());
        seckillOrderService.save(seckillOrder);

        redisTemplate.opsForValue().set("order:"+seckillOrder.getUserId()+":"+seckillOrder.getGoodsId(),seckillOrder);

        return order;
    }

    @Override
    public OrderDetailVo detail(Long orderId) {
        if(orderId==null){
            throw new GlobalException(RespBeanEnum.ORDER_NOT_EXIST);
        }
        Order order=orderMapper.selectById(orderId);
        GoodsVo goodsVo=goodsService.findGoodsVoByGoodsId(order.getGoodsId());
        OrderDetailVo orderDetailVo=new OrderDetailVo();
        orderDetailVo.setOrder(order);
        orderDetailVo.setGoodsVo(goodsVo);
        return orderDetailVo;
    }

    @Override
    public String createPath(User user, Long goodsId) {
        String str= MD5UTIL.md5(UUIDUtil.uuid()+"123456");
        redisTemplate.opsForValue().set("seckillPath:"+user.getId()+":"+goodsId,str,60, TimeUnit.SECONDS);
        return str;
    }

    @Override
    public Boolean checkPath(User user, Long goodsId, String path) {
        if(user==null||goodsId<0|| StringUtils.isEmpty(path)){
            return false;
        }
        String redisPath=(String) redisTemplate.opsForValue().get("seckillPath:"+user.getId()+":"+goodsId);
        return path.equals(redisPath);
    }

    @Override
    public Boolean checkCaptcha(User user, Long goodsId, String captcha) {
        String redisCaptcha=(String) redisTemplate.opsForValue().get("captcha:"+user.getId()+":"+goodsId);
        if(!redisCaptcha.equals(captcha)){
            return false;
        }
        return true;
    }
}
